package org.bonorsoft.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.bonorsoft.common.config.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WsAddressUtils {

    private static final Logger log = LoggerFactory.getLogger(WsAddressUtils.class);

    /**
     * 根据ip获取地址
     * @param ip
     * @return
     */
    public static String getAddress(String ip) {

        String address = "未知地点";

        // 内网不查询
        if (IpUtils.internalIp(ip))
        {
            return "内网IP";
        }
        if (Global.isAddressEnabled()){
            String url = "http://ip.ws.126.net/ipquery?ip=" + ip;
            String str = HttpUtil.get(url);
            if(StrUtil.hasBlank(str)){
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
            try
            {
                String substring = str.substring(str.indexOf("{"), str.indexOf("}")+1);
                System.out.println(substring);
                JSONObject jsonObject = JSONUtil.parseObj(substring);
                String province = jsonObject.getStr("province");
                String city = jsonObject.getStr("city");
                return province + " " + city;
            }
            catch (Exception e)
            {
                log.error("获取地理位置异常 {}", ip);
            }

        }

        return address;
    }

    public static void main(String[] args) {
        String ip = "223.99.22.139";
        String result = getAddress(ip);
        System.out.println(result);
        if(StrUtil.hasBlank("")){
            System.out.println(1);
        }
    }
}
